package jsf;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ex02")
public class ex02_LivroVisitas extends HttpServlet {

	private static final long serialVersionUID = 2165160604915514115L;

	List<String> visitas;  
	

	public ex02_LivroVisitas() {
		super();
		visitas = new ArrayList<String>();
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		
		String comentario = "Nome: <b> " + request.getParameter("nome") + "</b> <br />Comentário: <b> " + request.getParameter("comentario") + "</b><br />";
		
		
		if ((request.getParameter("nome") != null) && (!request.getParameter("nome").isEmpty() ))  {
			visitas.add(comentario);
		}

		request.setAttribute("nome", "");
		try {

			
			PrintWriter out = response.getWriter();
			response.setContentType("text/html");
			out.println("<html><body><head>");
			out.println("<meta charset='UTF-8'>");
			out.println("<title>Exercício 2</title>");
			out.println("</head>");

			out.println("<h1>Meu Livro de Visitas</h1>");
			out.println("<h3>Preencha o formulário para assinar</h3>");
			out.println("<form action='' method='POST' >");
			out.println("Nome: <input type='text' name='nome' size='40'><br />");
			out.println("Comentário: <input type='text' name='comentario' size='70'><br />");
			out.println("<p><input type='submit' value='Assinar' id='assinar'></p>");
			out.println("<br />");
			out.println("</form>");
			
			out.println("<h2>Comentários</h2>");
			out.println("<table width=500 border=1 style='border-collapse:collapse'>");
			for (String st : visitas) {
				out.println("<tr>");
				out.println("<td align='left'>"+st+"</td>");
				out.println("</tr>");
			}
			out.println("</table>");
			out.println("</body></html>");
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}